package com.uenpay.im.ui.old.activity.company;

import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.HttpInvokeResult;
import com.uenpay.im.invokeitems.BaseHttpInvokeItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * @author SL
 * @created 2016-2-22 13:52:22
 * @copyRight http://www.qiyunxin.com
 * @function 获取企业列表
 */
public class CompanyListInvokeItem extends BaseHttpInvokeItem {

	public class CompanyListInvokeItemResult extends HttpInvokeResult {
		public ArrayList<CompanyEntity> arrayList = new ArrayList<CompanyEntity>();
	}

	public CompanyListInvokeItemResult getOutPut() {
		return (CompanyListInvokeItemResult) GetResultObject();
	}

	/**
	 * 获取企业列表
	 * 
	 * @param type
	 *            1:获取我的企业列表
	 * @param myexist
	 *            :0 当前用户不在的企业 myexist:1 当前用户所在的企业 myexist:空 所有的企业
	 */
	public CompanyListInvokeItem(int type, int myexist) {
		String url = "";
		if (type == 1) {
			url = APIConfiguration.getBaseUrl()
					+ "Organization/Organization/myEntList?"
					+ APIConfiguration.getCustIdAndToken();
		} else {
			url = APIConfiguration.getBaseUrl()
					+ "Organization/Organization/allEntList?myexist=" + myexist
					+ "&" + APIConfiguration.getCustIdAndToken();
		}

		SetUrl(url);
	}

	@Override
	protected Object DeserializeResult(String responseBody) {
		CompanyListInvokeItemResult result = new CompanyListInvokeItemResult();
		try {
			JSONObject json = new JSONObject(responseBody);
			result.status = json.optInt("status");
			result.msg = json.optString("msg");

			JSONArray jsonarr = json.optJSONArray("data");
			if (jsonarr != null) {
				for (int i = 0, length = jsonarr.length(); i < length; i++) {
					result.arrayList.add(desCompanyEntity(jsonarr
							.optJSONObject(i)));
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
			return result;
		}

		return result;
	}

	private CompanyEntity desCompanyEntity(JSONObject json) {
		CompanyEntity companyEntity = new CompanyEntity();
		companyEntity._iscreator = json.optInt("_iscreator");
		companyEntity.custid = json.optString("custid");
		companyEntity.entname = json.optString("entname");
		companyEntity.entid = json.optInt("entid");
		companyEntity.owner = json.optString("owner");
		companyEntity.logo = json.optString("logo");
		companyEntity.status = json.optInt("status");
		companyEntity.createtime = json.optString("createtime");
		companyEntity.updatetime = json.optString("updatetime");
		return companyEntity;
	}

}
